/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.sophiadata.flink.sync.util;

import cn.hutool.db.DbUtil;
import cn.hutool.db.ds.simple.SimpleDataSource;
import com.alibaba.druid.pool.DruidDataSource;
import org.apache.flink.api.java.utils.ParameterTool;
import org.apache.flink.connector.jdbc.databases.mysql.catalog.MySqlCatalog;
import org.apache.flink.table.types.DataType;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.*;
import java.util.List;


import cn.hutool.db.Db;
import javax.sql.DataSource;
import java.sql.SQLException;

/** (@SophiaData) (@date 2023/5/31 19:02). */
public class MysqlUtil {

    private static final Logger LOG = LoggerFactory.getLogger(MysqlUtil.class);
    private static final String DRIVER_NAME = "com.mysql.cj.jdbc.Driver";

    public static Db getConnection(String url, String username, String password)
            throws ClassNotFoundException, SQLException {
        DruidDataSource ds = new DruidDataSource();
        ds.setUrl(url);
        ds.setUsername(username);
        ds.setPassword(password);
        ds.setDriverClassName(DRIVER_NAME);
        Db db;
        try {
            db = DbUtil.use(ds);
        } catch (Exception e) {
            LOG.error("使用HuTools创建链接失败: ", e);
            throw e;
        }
        return db;
    }


    public static MySqlCatalog useMysqlCatalog(ParameterTool params) {
        return new MySqlCatalog(
                Thread.currentThread().getContextClassLoader(), // MySQL 8 驱动
                // Class.forName("com.mysql.cj.jdbc.Driver").getClassLoader()
                "mysql-catalog",
                ParameterUtil.databaseName(params),
                ParameterUtil.username(params),
                ParameterUtil.password(params),
                String.format(
                        "jdbc:mysql://%s:%d",
                        ParameterUtil.hostname(params), ParameterUtil.port(params)));
    }
}
